package ca.etsmtl.log430.lab3;

import java.io.PipedReader;
import java.io.PipedWriter;

public class Copy extends Thread {
	boolean done;
	PipedReader inputPipe = new PipedReader();
	PipedWriter outputPipe = new PipedWriter();
	PipedWriter outputPipe1 = new PipedWriter();
	public Copy(PipedWriter inputPipe,
			PipedWriter outputPipe, PipedWriter outputPipe1) {

	
		try {

			// Connect inputPipe
			this.inputPipe.connect(inputPipe);
			
			// Connect outputPipe
			this.outputPipe = outputPipe;
			this.outputPipe1 = outputPipe1;

		} catch (Exception Error) {

		} // try/catch

	} // Constructor
	public void run() {

		// Declarations

		char[] characterValue = new char[1];
		// char array is required to turn char into a string
		String lineOfText = "";
		// string is required to look for the status code
		int integerCharacter; // the integer value read from the pipe

		try {

			done = false;

			while (!done) {

				integerCharacter = inputPipe.read();
				characterValue[0] = (char) integerCharacter;

				if (integerCharacter == -1) { // pipe is closed

					done = true;

				} else {

					if (integerCharacter == '\n') { // end of line
							
							lineOfText += new String(characterValue);
							outputPipe.write(lineOfText, 0, lineOfText.length());
							outputPipe.flush();
							
							outputPipe1.write(lineOfText, 0, lineOfText.length());
							outputPipe1.flush();

							lineOfText = "";

					} else {

						lineOfText += new String(characterValue);

					} // if //

				} // if

			} // while

		} catch (Exception error) {

			System.out.println("StatusFilter:: Interrupted.");

		} // try/catch

		try {

			inputPipe.close();
			System.out.println("StatusFilter:: input pipe closed.");

			outputPipe.close();
			outputPipe.close();
			System.out.println("StatusFilter:: output pipes closed.");

		} catch (Exception Error) {

			System.out.println("StatusFilter:: Error closing pipes.");

		} // try/catch

	} // run
}
